package com.vip.iot.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vip.iot.entity.IotAlarmCustom;
import com.vip.iot.entity.VehicleInfo;
import com.vip.iot.util.CommConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vip.iot.protocol.http.HttpClient.MethodPostResponse;

/**
 * 车辆定位，请求易流云SDK接口，获取响应数据，定时推送给kafka服务端
 *
 * @author wgb
 * @Date 2019/3/6
 */
@Slf4j
@Component
public class VehiclePositionService {
    private final Logger logger = LoggerFactory.getLogger(VehiclePositionService.class);
    @Value("${kafka.consumer.topic.vehicle}")
    private String vehicleLocationTopic;

    /**
     * 定时任务,kafka消息生产者，将接收到的MQTT消息以参数形式传进来调用发送消息方法,将消息推送给kafka服务器
     * 间隔时长30s
     */
//    @Scheduled(cron = "*/30 * * * * *")
    public void timedTesk() throws IOException {
        JSONObject AllVehickePositionOfJson = getAllVehicleInfoOfJson("-1");
        List<VehicleInfo> AllVehicleInfoOfList = getAllVehicleInfoOfList(AllVehickePositionOfJson);
//        sentMessageToKafka(vehicleLocationTopic,getNewestVehickePosition(AllVehicleInfoOfList,AllVehickePositionOfJson));
//        sentMessageToKafka(vehicleLocationTopic,new HandleRingInfo().createHandleRingInform());
    }

    /**
     * 获取车辆最新定位信息,添加到实体类对象IotAlarmCustom中，并将对象转换为json格式
     *
     * @param allVehicleInfoOfJson 所有的车辆信息，JSON格式
     * @param vehicleInfosOfList   所有的车辆信息，List格式
     * @return kafkaMessage 要推送的消息体
     */
    public String getNewestVehickePosition(List<VehicleInfo> vehicleInfosOfList, JSONObject allVehicleInfoOfJson) throws IOException {
        logger.info("获取车辆最新定位信息");
        String msgId = allVehicleInfoOfJson.getString("message");
        String state = allVehicleInfoOfJson.getString("code");
        IotAlarmCustom iotAlarmCustom = new IotAlarmCustom("location", "设备", state, vehicleInfosOfList);
        iotAlarmCustom.setMsgId(msgId);
        iotAlarmCustom.setStateDes(msgId);
        iotAlarmCustom.setCompanyCode("yly");
        return JSON.toJSONString(iotAlarmCustom);
    }

    /**
     * 临时方法：从车辆定位中获取前十条定位信息当做手环定位信息
     *
     * @param vehicleInfosOfList   所有的车辆信息，JSON格式
     * @param allVehicleInfoOfJson 所有的车辆信息，List格式
     * @return kafkaMessage 要推送的消息体
     */
    public String getHandleRingMessageFromVehickePosition(List<VehicleInfo> vehicleInfosOfList, JSONObject allVehicleInfoOfJson) {
        logger.info("获取手环定位信息");
        String msgId = allVehicleInfoOfJson.getString("message");
        List<VehicleInfo> data = vehicleInfosOfList;
        String state = allVehicleInfoOfJson.getString("code");
        List<VehicleInfo> handleRingList = data.subList(0, 10);
        IotAlarmCustom handleRingMessage = new IotAlarmCustom("location", "设备ID", state, handleRingList);
        handleRingMessage.setMsgId(msgId);
        handleRingMessage.setCompanyCode("hg");
        return JSON.toJSONString(handleRingMessage);
    }

    /**
     * 获取车辆信息的JSON格式
     *
     * @param vehicle 车牌号 -1为全部车辆
     * @return 获取指定车辆的定位结果封装的JSON
     */
    public static JSONObject getAllVehicleInfoOfJson(String vehicle) {
        Map<String, String> map = new HashMap<String, String>() {{
            put("timestamp", CommConfig.GetNowTime());
            put("format", CommConfig.Format);
            put("appkey", CommConfig.AppKey);
            put("method", "GetVehcileInfo");
            put("sessionid", "");
            put("vehicle", vehicle);
        }};
        map.put("sign", CommConfig.GetSign(map));
        String vehickePosition = MethodPostResponse(CommConfig.MotionBaseURL, map);
        JSONObject vehickePositionOfJson = JSON.parseObject(vehickePosition).getJSONObject("result");
        return vehickePositionOfJson;
    }

    /**
     * 转换json数据中的data为List格式
     *
     * @param vehickePositionOfJson 所有的车辆信息，JSON格式
     * @return
     */
    public List<VehicleInfo> getAllVehicleInfoOfList(JSONObject vehickePositionOfJson) {
        List<VehicleInfo> getAllVehicleInfoOfList = vehickePositionOfJson.getJSONArray("data").toJavaList(VehicleInfo.class);
        return getAllVehicleInfoOfList;
    }

    /**
     * 获取正在行驶的车辆车牌，此方法为了查询部分车辆的定位信息时，而获取部分车牌
     *
     * @param vehicleInfoOfList 所有的车辆信息，List格式
     * @return
     */
    public String getDrivingVehciles(List<VehicleInfo> vehicleInfoOfList) {
        StringBuffer vehicles = new StringBuffer();
        for (VehicleInfo vi : vehicleInfoOfList) {
            if (vi.getSpeed() > 0) {
                vehicles.append(vi.getVehicle() + ",");
            }
        }
        return vehicles.substring(0, vehicles.length() - 1);
    }

    /**
     * 获取停止的车辆车牌
     *
     * @param vehicleInfoOfList 所有车辆集合
     * @return
     */
    public String getStopedVeciles(List<VehicleInfo> vehicleInfoOfList) {
        StringBuffer vehicles = new StringBuffer();
        for (VehicleInfo vi : vehicleInfoOfList) {
            if (vi.getSpeed() == 0) {
                vehicles.append(vi.getVehicle() + ",");
            }
        }
        return vehicles.substring(0, vehicles.length() - 1);
    }

    /**
     * 获取免登易流云平台的密钥
     */
    public void getLoginFreeKey() {
        logger.info("获取免登易流云平台的密钥操作");
        Map<String, String> map = new HashMap<String, String>() {{
            put("method", "GetLoginStr");
            put("appkey", CommConfig.AppKey);
            put("timestamp", CommConfig.GetNowTime());
            put("format", CommConfig.Format);
        }};
        map.put("sign", CommConfig.GetSign(map));
        String loginFreeKey = MethodPostResponse(CommConfig.MotionBaseURL, map);
        System.out.println(loginFreeKey);
    }

    /**
     * 以地图模式获取车辆的最新位置信息
     *
     * @param vehicle 车牌号，支持同时查看
     */
    public String getNewestVehcileInfoMap(String vehicle) {
        logger.info("以地图模式获取车辆的最新位置信息操作");
        Map<String, String> map = new HashMap<String, String>() {{
            put("appkey", CommConfig.AppKey);
            put("timestamp", CommConfig.GetNowTime());
            put("vehicle", vehicle);
        }};
        String sign = CommConfig.GetSign(map);
        map.put("sign", sign);
        StringBuffer url = new StringBuffer();
        url.append(CommConfig.VehicleMap).append("appkey=").append(CommConfig.AppKey).append("&timestamp=").append(CommConfig.GetNowTime()).append("&vehicle=").append(vehicle).append("&sign=").append(sign);
        return url.toString();
    }
}
